package com.sphd.restaurantsystem.utils.updata;

import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.sphd.restaurantsystem.R;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Hu on 2017/1/17.
 */

public class UpDataUtils {

    private final int UPDATA_NONEED = 0;//不需要更新
    private final int UPDATA_CLIENT = 1;//通知用户更新
    private final int GET_UNDATAINFO_ERROR = 2;//获取信息出错
    private final int SDCARD_NOMOUNTED = 3;
    private final int DOWN_ERROR = 4;//下载出错
    private Context context;
    private String localVersion;//获取本地版本号
    String path = null;
    private UpdataInfo info;
    private boolean isAuto = false;
    Dialog loadingDialog, upDialog;

    public static final String FILE_NAME = "share_update";
    SharedPreferences.Editor editor;
    private String VER_REMEMBER = "ver_remember";//存储版本号
    private String TODAY_DATE = "today_date";
    private String today = null;
    private NotificationManager manager;
    private Notification notify;
    File file;

    public UpDataUtils(Context context, String msg) {
        this.context = context;
        loadingDialog = createLoadingDialog(context, msg);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        today = formatter.format(curDate);

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        editor = sp.edit();


    }

    public void checkUpAuto(String url) {
        try {
            isAuto = true;
            this.path = url;
            localVersion = getVersionName(context);
            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();
            loadingDialog.show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void checkUp(String url) {
        try {
            isAuto = false;
            this.path = url;
            localVersion = getVersionName(context);
            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();
            loadingDialog.show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 得到自定义的progressDialog
     *
     * @param context
     * @param msg
     * @return
     */
    public static Dialog createLoadingDialog(Context context, String msg) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局
        // main.xml中的ImageView
        ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                context, R.anim.load_animation);
        // 使用ImageView显示动画
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        tipTextView.setText(TextUtils.isEmpty(msg) ? "加载中……" : msg);// 设置加载信息

        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog

        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
        return loadingDialog;

    }

    public Dialog createMsgingDialog(Context context) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.up_msg, null);// 得到加载view
        TextView newVerNo = (TextView) v.findViewById(R.id.new_ver_no);// 版本号
        TextView newVerSize = (TextView) v.findViewById(R.id.new_ver_size);// 版本的大小
        TextView updateContent = (TextView) v.findViewById(R.id.update_content);// 版本更新内容
        try {
            newVerNo.setText("最新版本号：v" + info.getVersion());
        } catch (Exception e) {
            e.printStackTrace();
        }
        newVerSize.setText("最新版本大小：" + (TextUtils.isEmpty(info.getVersionsize()) ? "未知" : info.getVersionsize()));
        updateContent.setText(info.getDescription());
        CheckBox btnOverLook = (CheckBox) v.findViewById(R.id.btn_overlook);// 忽略选项
        Button confirmBtn = (Button) v.findViewById(R.id.confirm_button);// 确认
        Button cancelBtn = (Button) v.findViewById(R.id.cancel_button);// 确认
        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog
        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display d = wm.getDefaultDisplay(); // 获取屏幕宽、高用
        loadingDialog.setContentView(v, new LinearLayout.LayoutParams((int) (d.getWidth() * 0.85), ViewGroup.LayoutParams.WRAP_CONTENT));
        if (!TextUtils.isEmpty(info.getIsforce())) {
            if (!info.getIsforce().equals("1")) {
                btnOverLook.setVisibility(View.GONE);
                cancelBtn.setVisibility(View.GONE);
            }
        }
        if (!isAuto) {
            loadingDialog.setCancelable(true);// 不可以用“返回键”取消
            btnOverLook.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.GONE);
        }

        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下载
                upDialog.dismiss();
                toast("升级");
                downLoadNewApk();
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断checkBox的状态 如果是选中的状态 此版本不再提示
                if (btnOverLook.isChecked()) {
                    try {
                        put(VER_REMEMBER, getVersionName(context));
                        remove(TODAY_DATE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //非选中状态
                    put(TODAY_DATE, today);
                    remove(VER_REMEMBER);

                }
                upDialog.dismiss();

            }
        });

        return loadingDialog;

    }

    private void put(String key, Object object) {
        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        editor.commit();
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param key
     */
    public void remove(String key) {
        editor.remove(key);
        editor.commit();
    }

    /**
     * 下载apk
     *
     * @param
     */
//    private void downLoadNewApk(String apkUri, String version) {
    private void downLoadNewApk() {
        manager = (NotificationManager) context
                .getSystemService((context.NOTIFICATION_SERVICE));
        notify = new Notification();
        notify.icon = R.drawable.ic_launcher;
        // 通知栏显示所用到的布局文件
        notify.contentView = new RemoteViews(context.getPackageName(),
                R.layout.view_notify_item);
        manager.notify(100, notify);
        new Thread() {
            @Override
            public void run() {
                getFileFromServer();
            }
        }.start();


    }

    public void getFileFromServer() {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                URL url = new URL(info.getUrl());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                //获取到文件的大小
                InputStream is = conn.getInputStream();
                file = new File(Environment.getExternalStorageDirectory(), context.getPackageName() + ".apk");
                FileOutputStream fos = new FileOutputStream(file);
                BufferedInputStream bis = new BufferedInputStream(is);
                byte[] buffer = new byte[1024];
                int len;
                int total = 0;
                int temp = 0;
                while ((len = bis.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    total += len;
                    //获取当前下载量
                    // 通知更新进度（10,7,4整除才通知，没必要每次都更新进度）
                    // 当前进度
                    int schedule = (int) ((file.length() * 100) / conn.getContentLength());
                    if (temp != schedule
                            && (schedule % 10 == 0 || schedule % 4 == 0 || schedule % 7 == 0)) {
                        // 保证同一个数据只发了一次
                        temp = schedule;
                        completeHandler.sendEmptyMessage(schedule);
                    }

                }
                fos.close();
                bis.close();
                is.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            Message msg = new Message();
            msg.what = DOWN_ERROR;
            handlerupdate.sendMessage(msg);
        }
    }


    /**
     * 更新通知栏
     */
    private Handler completeHandler = new Handler() {
        public void handleMessage(Message msg) {
            // 更新通知栏
            if (msg.what < 100) {
                notify.contentView.setTextViewText(
                        R.id.notify_updata_values_tv, context.getPackageName() + ".apk正在下载……" + msg.what + "%");
                notify.contentView.setProgressBar(R.id.notify_updata_progress,
                        100, msg.what, false);
                manager.notify(100, notify);
            } else {
                notify.contentView.setTextViewText(
                        R.id.notify_updata_values_tv, context.getPackageName() + ".apk 下载完成");
                notify.contentView.setProgressBar(R.id.notify_updata_progress,
                        100, msg.what, false);// 清除通知栏
                manager.cancel(100);
                installApk();
            }
        }
    };


    //安装apk
    protected void installApk() {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 获取版本号
     */
    public static String getVersionName(Context context) throws Exception {
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageManager packageManager = context.getPackageManager();

        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),
                0);

        return packInfo.versionName;
    }

    public class CheckVersionTask implements Runnable {
        InputStream is;

        public void run() {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    // 从服务器获得一个输入流
                    is = conn.getInputStream();
                }
                info = UpdataInfoParser.getUpdataInfo(is);
                if (info.getVersion().equals(localVersion)) {
                    Message msg = new Message();
                    msg.what = UPDATA_NONEED;
                    handlerupdate.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.what = UPDATA_CLIENT;
                    handlerupdate.sendMessage(msg);
                }
            } catch (Exception e) {
                Message msg = new Message();
                msg.what = GET_UNDATAINFO_ERROR;
                handlerupdate.sendMessage(msg);
                e.printStackTrace();
            }
        }
    }

    Handler handlerupdate = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            loadingDialog.dismiss();
            switch (msg.what) {
                case UPDATA_NONEED:
                    //不需要版本更新
                    if (!isAuto) {
                        toast("暂无新版本");
                    }
                    break;
                case UPDATA_CLIENT:
                    //对话框通知用户升级程序
                    if (upDialog == null) {
                        upDialog = createMsgingDialog(context);
                    }

                    if (!isAuto) {
                        upDialog.show();
                    } else {
                        if (contains(TODAY_DATE)) {
                            if (!today.equals(get(TODAY_DATE, ""))) {
                                //提示
                                upDialog.show();
                            }
                        } else if (contains(VER_REMEMBER)) {
                            try {
                                if (!getVersionName(context).equals(get(VER_REMEMBER, ""))) {
                                    //提示
                                    upDialog.show();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            //提示
                            upDialog.show();
                        }

                    }


                    break;
                case GET_UNDATAINFO_ERROR:
                    //服务器超时
                    if (!isAuto)
                        toast("服务器超时");
                    break;
                case DOWN_ERROR:
                    //下载apk失败
                    if (!isAuto)
                        toast("下载应用失败，请稍后重试！");
                    break;
            }
        }
    };

    private void toast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 查询某个key是否已经存在
     *
     * @param
     * @param key
     * @return
     */
    public boolean contains(String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    public Object get(String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

}
